<?php
/**
 * Index.php
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 广西软甲士网络科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */

namespace app\api\controller;

use addon\coupon\model\CouponType;
use app\model\express\ExpressCompany;
use app\model\express\ExpressPackage;
use app\model\goods\Goods as GoodsModel;
use app\model\message\Message;
use app\model\order\Order as OrderModel;
use app\model\order\OrderCommon as OrderCommonModel;
use app\model\order\OrderRefund as OrderRefundModel;
use app\model\system\User as UserModel;
use think\facade\Config;
use think\facade\Db;
use EasyWeChat\Factory;
use think\facade\Log;

class Order extends BaseApi
{

    /**
     * 微信实例
     */
    protected $wx;

    /**
     * 微信配置
     */
    protected $config = [
        'app_id' => 'wx27ee55b0ea187a98',
        'secret' => '55105b37ebb93189dc8de30a3cb819e1',
        'response_type' => 'array',
        'log' => [
            'level' => 'debug',
            'file' => '/www/wwwroot/admin.chaozhiyu.cn/runtime/wechat.log',
        ],
    ];

    public function __construct()
    {
        parent::__construct();
        $this->wx = Factory::miniProgram($this->config);
    }


    /**
     * 待审核列表
     */
    public function check_lists()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        $order_common_model = new OrderCommonModel();

        //查询该审批人下面所有会员
        $next_member_ids = Db::name('member')->where('leader_member', $this->member_id)->column('member_id');
        //筛选待审核的,未支付的,已推送的
        $condition  = array(
            ["member_id", "in", $next_member_ids],
            ["site_id", "=", $this->site_id],
            ["is_delete", '=', 0],
            ["check", '=', 0],
            ["order_status", '=', 0],
            ["tip_leader", '=', 1],
        );

        $page_index = isset($this->params['page']) ? $this->params['page'] : 1;
        $page_size  = isset($this->params['page_size']) ? $this->params['page_size'] : PAGE_LIST_ROWS;
        $res        = $order_common_model->getMemberOrderPageList($condition, $page_index, $page_size, "create_time desc");
        return $this->response($res);
    }

    /**
     * 详情信息
     */
    public function detail()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        $order_common_model = new OrderCommonModel();
        $order_id           = isset($this->params['order_id']) ? $this->params['order_id'] : 0;
        $result             = $order_common_model->getMemberOrderDetail($order_id, $this->member_id, $this->site_id);
        return $this->response($result);
    }

    /**
     * 详情信息
     */
    public function check_detail()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        $order_common_model = new OrderCommonModel();
        $order_id           = isset($this->params['order_id']) ? $this->params['order_id'] : 0;
        $result             = $order_common_model->getMemberOrderCheckDetail($order_id, $this->member_id, $this->site_id);
        return $this->response($result);
    }

    /**
     * 列表信息
     */
    public function lists()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        $order_common_model = new OrderCommonModel();
        $condition          = array(
            ["member_id", "=", $this->member_id],
            ["site_id", "=", $this->site_id],
            ["is_delete", '=', 0]
        );
        $order_status       = isset($this->params['order_status']) ? $this->params['order_status'] : 'all';
        switch ($order_status) {
            case "waitpay"://待付款
                $condition[] = ["order_status", "=", 0];
                break;
            case "waitsend"://待发货
                $condition[] = ["order_status", "=", 1];
                break;
            case "waitconfirm"://待收货
                $condition[] = ["order_status", "in", [2, 3]];
                break;
            case "waitrate"://待评价
                $condition[] = ["order_status", "in", [4, 10]];
                $condition[] = ["is_evaluate", "=", 1];
                break;
        }
//		if (c !== "all") {
//			$condition[] = [ "order_status", "=", $order_status ];
//		}
        $page_index = isset($this->params['page']) ? $this->params['page'] : 1;
        $page_size  = isset($this->params['page_size']) ? $this->params['page_size'] : PAGE_LIST_ROWS;
        $res        = $order_common_model->getMemberOrderPageList($condition, $page_index, $page_size, "create_time desc");
        return $this->response($res);
    }

    /**
     * 订单评价基础信息
     */
    public function evluateinfo()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);

        $order_id = isset($this->params['order_id']) ? $this->params['order_id'] : 0;
        if (empty($order_id)) {
            return $this->response($this->error('', 'REQUEST_ORDER_ID'));
        }

        $order_common_model = new OrderCommonModel();
        $order_info         = $order_common_model->getOrderInfo([
            ['order_id', '=', $order_id],
            ['member_id', '=', $token['data']['member_id']],
            ['order_status', 'in', ('4,10')],
            ['is_evaluate', '=', 1],
        ], 'evaluate_status,evaluate_status_name');

        $res = $order_info['data'];
        if (!empty($res)) {
            if ($res['evaluate_status'] == 2) {
                return $this->response($this->error('', '该订单已评价'));
            } else {
                $condition   = [
                    ['order_id', '=', $order_id],
                    ['member_id', '=', $token['data']['member_id']],
                    ['refund_status', '<>', 3],
                ];
                $list        = $order_common_model->getOrderGoodsList($condition, 'order_goods_id,order_id,order_no,site_id,member_id,goods_id,sku_id,sku_name,sku_image,price,num');
                $list        = $list['data'];
                $res['list'] = $list;
                return $this->response($this->success($res));
            }
        } else {
            return $this->response($this->error('', '没有找到该订单'));
        }

    }

    /**
     * 订单收货(收到所有货物)
     */
    public function takeDelivery()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);

        $order_id = isset($this->params['order_id']) ? $this->params['order_id'] : 0;
        $img = isset($this->params['img']) ? $this->params['img'] : '';
        if (empty($order_id)) {
            return $this->response($this->error('', 'REQUEST_ORDER_ID'));
        }
        if (empty($img)) {
            return $this->response($this->error('', '请上传收货图片'));
        }
        $order_model = new OrderCommonModel();
        $result      = $order_model->orderCommonTakeDelivery($order_id, trim($img,','));
        return $this->response($result);
    }

    /**
     * 关闭订单
     */
    public function close()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);

        $order_id = isset($this->params['order_id']) ? $this->params['order_id'] : 0;
        if (empty($order_id)) {
            return $this->response($this->error('', 'REQUEST_ORDER_ID'));
        }
        $order_model = new OrderModel();
        $result      = $order_model->orderClose($order_id);
        return $this->response($result);
    }

    /**
     * 获取订单数量
     */
    public function num()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);

        if (empty($this->params['order_status'])) {
            return $this->response($this->error('', 'REQUEST_ORDER_STATUS'));
        }

        $order_common_model = new OrderCommonModel();
        $order_refund_model = new OrderRefundModel();

        $data = [];
        foreach (explode(',', $this->params['order_status']) as $order_status) {
            $condition = array(
                ["member_id", "=", $this->member_id],
            );
            switch ($order_status) {
                case "waitpay"://待付款
                    $condition[] = ["order_status", "=", 0];
                    break;
                case "waitsend"://待发货
                    $condition[] = ["order_status", "=", 1];
                    break;
                case "waitconfirm"://待收货
                    $condition[] = ["order_status", "in", [2, 3]];
                    break;
                case "waitrate"://待评价
                    $condition[] = ["order_status", "in", [4, 10]];
                    $condition[] = ["is_evaluate", "=", 1];
                    break;
            }
            if ($order_status == 'refunding') {
                $result              = $order_refund_model->getRefundOrderGoodsCount([
                    ["member_id", "=", $this->member_id],
                    ["refund_status", "not in", [0, 3]]
                ]);
                $data[$order_status] = $result['data'];
            } else {
                $result              = $order_common_model->getOrderCount($condition);
                $data[$order_status] = $result['data'];
            }
        }
        return $this->response(success(0, '', $data));
    }

    /**
     * 订单包裹信息
     */
    public function package()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        $order_id              = isset($this->params['order_id']) ? $this->params['order_id'] : '';//订单id
        $express_package_model = new ExpressPackage();
        $condition             = array(
            ["member_id", "=", $this->member_id],
            ["order_id", "=", $order_id],
        );
        $result                = $express_package_model->package($condition);
        if ($result) return $this->response($this->success($result));
        else return $this->response($this->error());
    }

    /**
     * 订单支付
     * @return string
     */
    public function pay()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        $order_ids = isset($this->params['order_ids']) ? $this->params['order_ids'] : '';//订单id
        if (empty($order_ids)) return $this->response($this->error('', "订单数据为空"));
        //判断是否审批，未审批的订单不能支付
        if (!Db::name('order')->where('order_id', $order_ids)->value('check')){
            return $this->response($this->error('','订单尚未审批，无法支付'));
        }
        $order_common_model = new OrderCommonModel();
        $result             = $order_common_model->splitOrderPay($order_ids);
        return $this->response($result);
    }

    /**
     * 订单审批
     */
    public function sign()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);

        if (empty($this->params['order_id'])) return $this->response($this->error('', "订单号不存在"));

        //检查自己是否是订单的审批人
        $member_id = Db::name('order')->where('order_id', $this->params['order_id'])->value('member_id');
        $mobile = Db::name('member')->where('member_id', $member_id)->value('mobile');
        $leader_member = Db::name('member')->where('member_id', $member_id)->value('leader_member');
        if ($this->member_id <> $leader_member){
            return $this->response($this->error('', "对不起，该订单的审批人不是您！"));
        }
        //查询订单
        $order = Db::name('order')->where('order_id', $this->params['order_id'])->find();
        //检查订单推送状态
        if ($order['tip_leader'] == 0){
            return $this->response($this->error('', "对不起，管理员尚未将该订单推送给审批员！"));
        }
        //检查订单审批状态
        if ($order['check']){
            return $this->response($this->error('', "该订单已经处理过，请勿重复操作！"));
        }
        //检查订单状态
        if ($order['order_status'] <> 0){
            return $this->response($this->error('', "只能审批未支付的订单！"));
        }
        //如果拒绝审批
        if (isset($this->params['deny']) && $this->params['deny'] == 1){
            //关闭订单
            (new OrderCommonModel())->orderClose($this->params['order_id']);
            //状态改为已拒绝
            Db::name('order')->where('order_id', $this->params['order_id'])->update([
                'check'      =>  2,
            ]);

            //给订单人发拒绝通知
            if (!empty($mobile)){
                (new Message())->send_sms($mobile,'1132702', [$order['order_no']]);
            }

            //20210922，给多个管理员发失败通知
            sendEmail(4, $order['order_no']);

            return $this->response($this->success('', "拒绝审批成功"));
        }
        if (empty($this->params['sign_img'])) return $this->response($this->error('', "请先上传签名图片"));

        //开始审批
        Db::name('order')->where('order_id', $this->params['order_id'])->update([
           'check'      =>  1,
           'check_img'  =>  $this->params['sign_img'],
        ]);

        //给订单人发成功通知
        if (!empty($mobile)){
            (new Message())->send_sms($mobile,'1132704', [$order['order_no']]);
        }

        //20210922，给多个管理员发成功通知
        sendEmail(3, $order['order_no']);

        return $this->response($this->success());
    }

    /**
     * 供应商订单列表
     */
    public function offer_order_lists()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $order_common_model = new OrderCommonModel();
        $page_index = input('page', 1);
        $page_size = input('page_size', PAGE_LIST_ROWS);
        $condition = [
            //只能查找已审核，未删除，供应商为自己的订单
            ["check", "=", 1],
            ["offer_member", "=", $this->uid],
            ["site_id", "=", 1],
            ['is_delete', '=', 0],
            ['review', '=', 1],
        ];
        $list = $order_common_model->getOfferOrderPageList($condition, $page_index, $page_size, "create_time desc");
        return $this->response($list);
    }

    /**
     * 供应商商品报价列表
     */
    public function offer_goods_lists()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);

        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $goods_model = new GoodsModel();

        $page_index  = isset($this->params['page']) ? $this->params['page'] : 1;
        $page_size   = isset($this->params['page_size']) ? $this->params['page_size'] : PAGE_LIST_ROWS;
        $search_text = input('keyword', "");
        $min_price = input('min_price', 0);
        $max_price   = input('max_price', 0);
        $goods_class = input('goods_class', "");
        $label_id    = input('label_id', "");
        $class_id    = input('class_id', "");
        $category_id = input('category_id', "");
        $offer_type  = input('offer_type', '');
        $order       = input('order', "");

        $condition = [['gs.is_delete', '=', 0], ['gs.site_id', '=', $this->site_id]];

        if (!empty($offer_type)) {
            if ($offer_type == 1) {
                $condition[] = ['o.offer_member', '=', $this->uid];
            } else {
                $condition[] = ['o.offer_member', '=', null];
            }
        } else {
            $condition[] = ['o.offer_member', 'exp', Db::raw(
                'IS NULL OR o.offer_member='.$this->uid.' OR 
                    (o.offer_member<>'.$this->uid.' AND 
                    gs.sku_id NOT IN (select sku_id from shop_offer where offer_member='.$this->uid.'))
                ')];
        }

        if (!empty($search_text)) {
            $condition[] = ['gs.sku_name', 'like', '%' . $search_text . '%'];
        }

        if (!empty($category_id)) {
            $condition[] = ['g.category_id', 'like', [$category_id, '%'.$category_id.',%', '%'.$category_id, '%,'.$category_id.',%'], 'or'];
        }

        if ($goods_class !== "") {
            $condition[] = ['gs.goods_class', '=', $goods_class];
        }

        if ($class_id !== "") {
            $condition[] = ['gs.goods_attr_class', '=', $class_id];
        }

        if (!empty($label_id)) {
            $condition[] = ['g.label_id', '=', $label_id];
        }

        if (!empty($min_price)) $condition[] = ['gs.price', '>=', $min_price];
        if (!empty($max_price)) $condition[] = ['gs.price', '<=', $max_price];

        if ($order == 'sale_num') {
            $order_by = 'gs.sale_num desc';
        } else if ($order == 'discount_price') {
            $order_by = 'gs.price desc';
        } else {
            $order_by  = 'gs.create_time desc';
        }

        $field     = 'gs.sku_id,gs.sku_name,gs.price as sku_price,gs.sku_image,gs.sku_images,o.id as offer_id,o.offer_member,o.price as offer_price,
                      min(o.price) as min_offer_price,max(o.price) as max_offer_price,sum(o.stock) as offer_stock,o.update_time';
        $alias     = 'gs';
        $join      = [
            ['offer o', 'gs.sku_id = o.sku_id', 'left'],
            ['goods g', 'g.sku_id = gs.sku_id', 'left'],
        ];

        $group_by = 'gs.sku_id';

        $res  = $goods_model->getGoodsSkuPageList($condition, $page_index, $page_size, $order_by, $field, $alias, $join, $group_by);

        if (!empty($res['data']['list'])) {
            foreach ($res['data']['list'] as $k => $v) {
                if ($v['offer_member'] <> $this->uid) {
                    $res['data']['list'][$k]['offer_price'] = '无';
                    $res['data']['list'][$k]['offer_stock'] = '无';
                    $res['data']['list'][$k]['update_time'] = '无';
                } else {
                    if ($v['min_offer_price'] == $v['max_offer_price']) {
                        $res['data']['list'][$k]['offer_price'] = $v['min_offer_price'] ?? '无';
                    } else {
                        $res['data']['list'][$k]['offer_price'] = $v['min_offer_price'].' ~ '.$v['max_offer_price'] ?? '无';
                    }
                    $res['data']['list'][$k]['offer_stock'] = $v['offer_stock'] ?? '无';
                    $res['data']['list'][$k]['update_time'] = $v['update_time'] ? date('Y-m-d H:i:s', $v['update_time']) : '无';
                }

                // 商品零售价拦截更改
                // 如果有供应商报价就是当前售价，如果没有就是商品原价
                $res['data']['list'][$k]['sku_price'] = getGodPrice($v['sku_id']);
            }
        }

        return $this->response($res);
    }

    /**
     * 20211009-添加区域报价
     */
    public function offer_set_location()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $sku_id = intval(input('sku_id', 0));
        $province_id = intval(input('province_id', 0));
        $city_id = intval(input('city_id', 0));
        $district_id = intval(input('district_id', 0));
        $price = floatval(input('price', 0));
        $stock = intval(input('stock', 0));

        $goods_model = new GoodsModel();
        $result = $goods_model->goods_location($sku_id, $province_id, $city_id, $district_id, $price, $stock, $this->uid);
        return $this->response($result);
    }

    // 20210929-获取区域报价
    public function offer_get_location()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $sku_id = intval(input('sku_id', 0));

        $goods_model = new GoodsModel();
        $result = $goods_model->offer_get_location($sku_id, $this->uid);
        return $this->response($result);
    }

    // 20211009-删除区域报价
    public function offer_delete_location()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $id = intval(input('id', 0));

        $goods_model = new GoodsModel();
        $result = $goods_model->offer_delete_location($id, $this->uid);
        return $this->response($result);
    }

    /**
     * 供应商信息设置
     */
    public function offer_setting()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $offer_name      = input("offer_name", 0);
        $offer_business_license      = input("offer_business_license", '');
        $offer_person      = input("offer_person", '');
        $offer_mobile      = input("offer_mobile", '');
        $province_id      = input("province_id", '');
        $city_id      = input("city_id", '');
        $district_id      = input("district_id", '');
        $address      = input("address", '');
        $full_address      = input("full_address", '');
        $latitude      = input("latitude", '');
        $longitude      = input("longitude", '');
        $group_id      = input("group_id", 5);

        $condition = array(
            ["uid", "=", $this->uid],
            ["site_id", "=", 1],
            ["app_module", "=", $this->app_module],
        );
        $data      = array(
            'offer_name'    =>  $offer_name,
            'offer_business_license'    =>  $offer_business_license,
            'offer_person'    =>  $offer_person,
            'offer_mobile'    =>  $offer_mobile,
            'province_id'    =>  $province_id,
            'city_id'    =>  $city_id,
            'district_id'    =>  $district_id,
            'address'    =>  $address,
            'full_address'    =>  $full_address,
            'latitude'    =>  $latitude,
            'longitude'    =>  $longitude,
            'group_id'     =>   $group_id,
        );
        $user_model = new UserModel();
        $result = $user_model->editUser($data, $condition);
        return $this->response($result);
    }

    /**
     * 供应商订单发货
     */
    public function offer_delivery()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $order_model = new OrderModel();
        $data = array(
            "type" => 'manual',//发货方式（手动发货、电子面单）
            "order_goods_ids" => input("order_goods_ids", ''),//商品id
            "express_company_id" => input("express_company_id", 0),//物流公司
            "delivery_no" => input("delivery_no", ''),//快递单号
            "order_id" => input("order_id", 0),//订单id
            "delivery_type" => input("delivery_type", 0),//是否需要物流
            "site_id" => 1,
            "template_id" => 0//电子面单模板id
        );
        $result = $order_model->orderGoodsDelivery($data, 1, $this->uid);
        return $this->response($result);
    }

    /**
     * 供应商-查询可用物流公司
     */
    public function getShopExpressCompanyList()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $express_company_model = new ExpressCompany();
        //店铺物流公司
        $result = $express_company_model->getExpressCompanyList([["site_id", "=", 1]]);
        return $this->response($result);
    }

    /**
     * 供应商-获取订单项列表
     */
    public function getOrderGoodsList()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $order_id = input("order_id", 0);
        $delivery_status = input("delivery_status", '');
        $order_common_model = new OrderCommonModel();
        $condition = array(
            ["order_id", "=", $order_id],
            ["site_id", "=", 1],
            ["refund_status", "<>", 3],
            //2020-11-10新增 供应商只能查看自己的那部分商品
            ["offer_member", "=", $this->uid],
        );
        if ($delivery_status != '') {
            $condition[] = ["delivery_status", "=", $delivery_status];
        }
        $field = "order_goods_id, order_id, site_id, sku_name, sku_image, sku_no, is_virtual, price, cost_price, num, goods_money, cost_money, delivery_status, delivery_no, goods_id, delivery_status_name";
        $result = $order_common_model->getOrderGoodsList($condition, $field, '', null, "");
        return $this->response($result);
    }

    /**
     * 供应商-获取订单信息
     */
    public function getOrderInfo()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $order_id = input("order_id", 0);
        $order_common_model = new OrderCommonModel();
        $condition = array(
            ["order_id", "=", $order_id],
            ["site_id", "=", 1],
        );
        $result = $order_common_model->getOrderInfo($condition);
        return $this->response($result);
    }

    /**
     * 20211018-区域批量报价
     */
    public function offer_batch_set_location()
    {
        $token = $this->checkToken();
        if ($token['code'] < 0) return $this->response($token);
        if (empty($this->uid)){
            return $this->response($this->error('','对不起，您不是供应商'));
        }

        $province_id = intval(input('province_id', 0));
        $city_id = intval(input('city_id', 0));
        $district_id = intval(input('district_id', 0));

        $sku_list = input('sku_list', '');
        if (!is_json($sku_list)) return $this->response($this->error('','报价商品数据必须是json格式'));
        $sku_list = json_decode($sku_list, true);

        $goods_model = new GoodsModel();
        $result = $goods_model->goods_batch_location($province_id, $city_id, $district_id, $sku_list, $this->uid);
        return $this->response($result);
    }
}